package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

func main() {

	var wg = sync.WaitGroup{}
	t1 := time.Now()
	//ctx, cancel := context.WithCancel(context.Background())
	//ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second))
	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second))
	//time.Now().AddDate(0, 1)
	wg.Add(1)
	go func() {
		ip, err := getIpOther(ctx, &wg)
		fmt.Println(ip, err)
	}()

	cancel()

	//go func() {
	//	time.Sleep(2 * time.Second)
	//	//取消协程
	//	//cancel()
	//}()

	wg.Wait()
	fmt.Println("执行！结束")
	fmt.Println("执行！完成时间：", time.Since(t1))
}

func getIpOther(ctx context.Context, wg *sync.WaitGroup) (ip string, err error) {
	go func() {
		select {
		case <-ctx.Done():
			fmt.Println("协程！取消", ctx.Err())
			err = ctx.Err()
			wg.Done()
			return
		}
	}()
	time.Sleep(4 * time.Second)
	ip = "192.168.100.200"
	wg.Done()
	return
}
